<!--  -->
<template>
  <div style="padding-top:100px">
    <div class="app-title-container title-position">
      <modules-title titleName="稳定性方案">
        <template slot="btn">
          <el-button class="filter-item" plain="" icon="el-icon-refresh-left" size="small"
                     @click="handleBack">返回
          </el-button>
          <el-button class="filter-item" type="primary" icon="el-icon-check" size="small"
                     @click="handleSave">保存
          </el-button>
          <el-button class="filter-item" type="primary" icon="el-icon-check" size="small"
                     @click="handleSubmit">
            <span v-if="$route.query.type != 2">提交审批</span>
            <span v-else>提交变更审批</span>
          </el-button>
        </template>
      </modules-title>
    </div>

    <div style="padding:20px">

      <el-form ref="ruleForm" label-position="left" :model="ruleForm" :rules="rules">
        <!--基本信息-->
        <el-row :gutter="50">
          <el-col :span="6">
            <el-form-item label="方案名称：" prop="scheme_name" label-width="95px">
              <el-input v-model="ruleForm.scheme_name" :disabled="disabled" placeholder="请输入方案名称"/>
            </el-form-item>
          </el-col>

          <el-col :span="6" v-if="$route.query.id">
            <el-form-item label="方案编号：" prop="scheme_no" label-width="95px">
              <el-input v-model="ruleForm.scheme_no" :disabled="disabled" placeholder="请输入方案编号"/>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="方案所属项目：" prop="scheme_project_id" label-width="120px">

              <el-select v-if="!disabled" v-model="ruleForm.scheme_project_id" placeholder="请选择方案所属项目"
                         style="width:100%" @change="handlProject">
                <el-option v-for="(item,index) in projectList" :key="index + 'o'"
                           :label="item.project_name" :value="item.id">
                </el-option>
              </el-select>
              <el-input v-else v-model="ruleForm.scheme_project_name" disabled/>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="版本号：" prop="version_no" label-width="95px">
              <el-input v-model="ruleForm.version_no" placeholder="请输入版本号"/>
            </el-form-item>
          </el-col>
        </el-row>

        <!--稳定性方案明细-->
        <item-title title="稳定性方案明细" :borderShow="false"/>
        <div class="card">
          <el-row :gutter="50">
            <el-col :span="6">
              <el-card shadow="nerver">
                <p style="text-align: center;margin:0;line-height: 40px;">
                  已选
                </p>
                <div id="scrollbox">
                  <el-tree :data="conditionsInve" :props="defaultProps" default-expand-all>
                    <span class="custom-tree-node" slot-scope="{ node, data }">
                      <span>{{ node.label }}</span>
                      <span>
                        <el-button type="text" v-if="handlShow(node)" size="medium"
                                   @click="() => remove( data)">
                          <i style="color:red" class="el-icon-delete-solid"></i>
                        </el-button>
                      </span>
                    </span>
                  </el-tree>
                </div>

              </el-card>
            </el-col>

            <el-col :span="6">
              <el-card shadow="nerver">
                <p style="text-align: right;margin:0;line-height: 40px;">
                  <el-button type="text" size="medium " @click="hanldAdd"
                             :disabled="$route.query.type == 2" class="el-icon-document-add">添加样品
                  </el-button>
                </p>
                <div id="scrollbox">
                  <el-checkbox-group v-model="checlSamp" @change="handlSamp"
                                     :disabled="$route.query.type == 2">
                    <ul class="ul">
                      <li style="display: flex;justify-content: space-between;"
                          v-for="(item,index) in sampleList" :key="item.id">
                        <div>
                          <el-checkbox :label="item.id">
                            {{item.sample_name}}
                          </el-checkbox>
                        </div>
                        <div>
                          <el-button type="text" icon="el-icon-edit" size="medium"
                                     :disabled="$route.query.type == 2" @click="handleEdit(index)">
                          </el-button>
                          <el-button style="color:red" type="text" icon="el-icon-delete-solid"
                                     :disabled="$route.query.type == 2" size="medium"
                                     @click="handleDelete(index)">
                          </el-button>
                        </div>
                      </li>
                    </ul>
                  </el-checkbox-group>
                </div>
              </el-card>
            </el-col>

            <el-col :span="6">
              <el-card shadow="nerver">
                <p style="text-align: center;margin:0;line-height: 40px;">
                  设置考察类型</p>
                <div id="scrollbox">
                  <Investigation ref="Investigation" :conditions-inve="conditionsInve"
                                 @sucess="sucess"/>
                </div>
              </el-card>
            </el-col>

            <el-col :span="6">
              <el-card shadow="nerver">
                <p style="text-align: center;margin:0;line-height: 40px;">
                  设置放置条件
                </p>
                <div id="scrollbox">
                  <conditions :conditions-inve="conditionsInve" :tabs-index="tabsIndex"
                              @sucessTab="sucessTab" ref='conditions'/>
                </div>
              </el-card>
            </el-col>

          </el-row>
        </div>

        <!--稳定性仪器信息-->
        <item-title title="稳定性仪器信息" :borderShow="false"/>
        <el-row :gutter="10">
          <el-col :span="6">
            <el-form-item>
              <el-input v-model="ruleForm.instrument" placeholder="仪器编号,仪器名称搜索"/>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item>
              <el-button class="filter-item" plain="" icon="el-icon-plus" size="small"
                         @click="handleAddList">添加到列表
              </el-button>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form :model="formTable" :rules="formRules" class="demo-ruleForm">
              <el-table :data="formTable.tableData" class="table1" border style="width: 100%">
                <el-table-column prop="instrument_no" label="编号" align="center"/>

                <el-table-column prop="instrument_name" label="仪器名称" align="center"/>

                <el-table-column prop="brand_model" label="品牌类型" align="center"/>

                <el-table-column label="参数设置" align="center">
                  <template slot-scope="scope">
                    <el-form-item class="item_form" :prop="'tableData.'+scope.$index + '.attrs'"
                                  :rules="formRules.attrs ">
                      <el-input v-model.number="scope.row.attrs">
                      </el-input>
                    </el-form-item>
                  </template>
                </el-table-column>

              </el-table>
            </el-form>
          </el-col>
        </el-row>

      </el-form>
      <div style="text-align: center;margin-top:20px">
        <el-button class="filter-item" plain="" icon="el-icon-d-arrow-right" size="small"
                   @click="handlNextStep">
          下一步,设置检验项目信息
        </el-button>
      </div>
      <!--对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body
                 :before-close="cancel" :close-on-click-modal="false" v-if="open">
        <el-form ref="formOpen" :model="formOpen" :rules="openRules" label-width="120px"
                 size="small">
          <el-form-item label="样品名称" prop="sample_name">
            <el-input v-model.trim="formOpen.sample_name" placeholder="请输入样品名称"/>
          </el-form-item>

          <el-form-item label="样品类型" prop="sample_type_info.same_type_id">
            <el-select v-model="formOpen.sample_type_info.same_type_id" placeholder="请选择样品类型"
                       style="width:100%" @change="handlSampleType">
              <el-option v-for="(item,index) in sampleType" :key="index + 'o4'"
                         :label="item.sample_type_name" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="样品批号" prop="sample_batch">
            <el-input v-model.trim="formOpen.sample_batch" placeholder="请输入样品批号"/>
          </el-form-item>

          <el-form-item label="样品规格" prop="packaging_nu">
            <el-row :gutter="15">
              <el-col :span="7">
                <el-input v-model.number="formOpen.packaging_nu" placeholder="请输入样品规格"/>
              </el-col>
              <el-col :span="5">
                <el-input v-model.trim="formOpen.packaging_nu_unit" ref="packaging_nu_unit"
                          style="width:70%"/>
                <span style="padding-left:20px">/</span>
              </el-col>
              <el-col :span="9">
                <span style="width:60%;padding-right:15px">包装单位</span>
                <el-input v-model.trim="formOpen.packaging_unit" ref="packaging_unit"
                          style="width:50%"/>
              </el-col>
              <el-col :span="2">
                <el-tooltip content="填写包装单位，可不填写前两个，如果填写前两个任意一个，三个输入框必填" placement="bottom"
                            effect="light">
                  <i class="el-icon-question"></i>
                </el-tooltip>

              </el-col>
            </el-row>
          </el-form-item>

          <el-form-item label="生产厂家" prop="producer">
            <el-input v-model="formOpen.producer" placeholder="请输入生产厂家"/>
          </el-form-item>
        </el-form>

        <div slot="footer" class="dialog-footer">
          <el-button plain size="small" @click="cancel">取 消
          </el-button>
          <el-button plain size="small" v-if="!openType" @click="handlSaveAdd">保存并继续添加
          </el-button>
          <el-button size="small" type="primary" @click="submitForm">
            保 存
          </el-button>
        </div>
      </el-dialog>

      <el-dialog title="变更说明" :visible.sync="openChange" width="600px" append-to-body
                 :before-close="cancelChange" :close-on-click-modal="false" v-if="openChange">
        <el-form :model="openChangeForm" ref="openChangeForm" label-width="100px">
          <el-form-item label="变更原因" prop="change_reason"
                        :rules="[{ required: true, message: '请填写变更原因', trigger: 'blur' }]">
            <el-input type="textarea" v-model="openChangeForm.change_reason"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button plain size="small" @click="cancelChange">取 消
          </el-button>
          <el-button size="small" type="primary" @click="submitChange">
            确 定
          </el-button>
        </div>
      </el-dialog>

    </div>
  </div>
</template>

<script>
  import {
    sampleDown,
    projectId,
    projectList,
    createSave,
    updateSave,
    updateChangeSave,
    stabilityEditor,
    subApproval,
    submitChange
  } from '@/api/stability/giveUp'

  export default {
    components: {
      Investigation: () => import('../../components/Investigation.vue'),
      conditions: () => import('../../components/conditions.vue')
    },
    data() {
      let checkName = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入样品名称'))
        } else {
          if (this.sampleList.length > 0) {
            let index = this.sampleList.findIndex(a => a.sample_name === value)
            if (index !== -1) {
              if (index === this.openIndex) {
                callback()
              } else {
                callback(new Error('样品名称已存在'))
              }
            } else {
              callback()
            }
          } else {
            callback()
          }
        }
      }
      let checkSpeci = (rule, value, callback) => {
        let packaging_nu_unit = this.$refs.packaging_nu_unit.value
        let packaging_unit = this.$refs.packaging_unit.value

        if (value && packaging_nu_unit && packaging_unit) {
          callback()
        } else {
          callback(new Error('请输入包装单位'))
        }
      }
      return {
        disabled: false,
        defaultProps: {
          children: 'conditions',
          label: 'label'
        },
        projectList: [], //方案所属项目
        ruleForm: {
          sign_category_id:'',
          sign_category_name:'',
          id: '',
          scheme_name: '', //"方案名称",
          scheme_no: '', //"方案编号",
          scheme_project_id: '', //"方案所属项目id",
          scheme_project_name: '', // "方案所属项目名称",
          project_leader_id: '', // "项目负责人id",
          project_no: '',
          project_leader_name: '', //"项目负责人名称",
          version_no: '', //"版本号"
          stability_instrument_infos: [],
          stability_details: [],
          sample_list: [],
          sample_id: '1'
        },
        rules: {
          scheme_name: [
            { required: true, message: '请填写方案名称', trigger: 'blur' }
          ],
          scheme_no: [
            { required: true, message: '请填写方案编号', trigger: 'blur' }
          ],
          scheme_project_id: [
            { required: true, message: '请选择方案所属项目', trigger: 'chenge' }
          ],
          version_no: [
            { required: true, message: '请填写版本号', trigger: 'blur' }
          ]
        },
        options: [],
        sampleType: [], //样品类型
        sampleList: [], //添加样品数组
        checlSamp: [],
        checkList: [],
        InvestigationList: [], //考察类型数组
        placeConditionsList: [], //放置条件数组
        conditionsInve: [],
        tabsIndex: 0,
        checkListData: [
          {
            index: '8',
            list: [2332],
            children: [{ index: '8', list: [2332] }]
          }
        ],
        open: false,
        title: '',
        formOpen: {
          sample_name: '',
          sample_type_info: {
            same_type_id: '', //"样品类型id",
            same_type_name: '', //"样品类型名称",
            inspect_projects: []
          },
          sample_batch: '',
          packaging_nu: null,
          packaging_unit: '',
          packaging_nu_unit: '',
          sample_attrs: '',
          producer: '',
          id: 1
        },
        openRules: {
          sample_name: [
            { required: true, validator: checkName, trigger: 'blur' }
          ],
          'sample_type_info.same_type_id': [
            { required: true, message: '请选择样品类型', trigger: 'change' }
          ],
          sample_batch: [
            { required: true, message: '请填写样品批号', trigger: 'blur' }
          ],
          producer: [
            { required: true, message: '请填写生产厂家', trigger: 'blur' }
          ],
          packaging_nu: [{ required: true, validator: checkSpeci }]
        },
        openIndex: undefined,
        openType: false,
        formTable: {
          tableData: [
            {
              id: '2', //仪器id",
              instrument_name: 'cdd', //仪器名称",
              instrument_no: '654', //仪器编号",
              brand_model: '西门子', //品牌型号",
              attrs: '22', //参数设置",
              locker_id: '', //保管员id",
              locker_name: '' //保管员名称"
            }
          ]
        },
        formRules: {
          attrs: [{ required: true, trigger: 'blur' }]
        },
        id: '',
        openChange: false,
        openChangeForm: {
          id: '',
          change_reason: ''
        }
      }
    },
    //是计算属性，也可以理解为一个方法。
    computed: {},
    //属性是手动定义的所需监听的值
    watch: {},
    //生命周期 - 创建完成（访问当前this实例）
    created() {
      this.projectListData()
      this.sampleDownData()
      if (this.$route.query.id) {
        this.disabled = true
        this.handlEditor()
      } else {
        this.disabled = false
      }
    },
    //生命周期 - 挂载完成（访问DOM元素）
    mounted() {
    },
    //是Vue实例对象上绑定的方法，供当前Vue组件作用域内使用，
    methods: {
      //获取编辑数据
      handlEditor() {
        stabilityEditor(this.$route.query.id).then(res => {
          if (res.code === 200) {
            this.ruleForm = res.data || []
            this.formTable.tableData = res.data.stability_instrument_infos || []
            let arr = [],
              bbb = []
            arr = res.data.stability_details || []
            arr.forEach((item, index) => {
              bbb.push(item.stability_sample_info)
            })
            this.sampleList = res.data.sample_list || []
            this.ruleForm.sample_list = this.sampleList
            this.handlSampID()
            bbb.forEach(item => {
              this.checlSamp.push(item.id)
            })
            this.conditionsInve = res.data.stability_details
          }
        })
      },
      //方案所属项目
      projectListData: function() {
        projectList().then(res => {
          if (res.code === 200) {
            this.projectList = res.data.data || []
          }
        })
      },

      //设置考察组件
      sucess: function(val) {
        if (this.tabsIndex != val) {
          this.$refs.conditions.ssss()
        }
        this.tabsIndex = Number(val)
      },

      //放置条件组件
      sucessTab: function(val) {
      },

      //方案所属项目事件
      handlProject: function(val) {
        this.projectList.forEach(item => {
          if (item.id === val) {
            this.ruleForm.scheme_project_name = item.project_name
            this.ruleForm.project_leader_id = item.project_person_in_charge_id
            this.ruleForm.project_leader_name = item.project_person_in_charge
            this.ruleForm.project_no = item.project_no
            this.ruleForm.sign_category_name = item.sign_category_name;
            this.ruleForm.sign_category_id = item.sign_category_id;


          }
          
        })
        if (val !== '') {
          this.$nextTick(() => {
            this.$refs.ruleForm.clearValidate('scheme_project_id')
          })
        }
      },

      //获取样品类型
      sampleDownData: function() {
        sampleDown().then(res => {
          if (res.code === 200) {
            this.sampleType = res.data || []
          }
        })
      },

      //样类型change事件
      async handlSampleType(val) {
        let arr = []
        await projectId(val).then(res => {
          if (res.code === 200) {
            arr = res.data || []
          }
        })
        this.sampleType.forEach(item => {
          if (item.id === val) {
            this.formOpen.sample_type_info = {
              same_type_id: val,
              same_type_name: item.sample_type_name,
              inspect_projects: arr
            }
          }
        })
      },

      //返回
      handleBack: function() {
        this.$router.push('/stability/giveUp')
      },

      //保存
      handleSave: function() {
        return new Promise((resolve, reject) => {
          this.ruleForm.stability_instrument_infos = this.formTable.tableData
          this.ruleForm.stability_details = this.conditionsInve
          this.$refs.ruleForm.validate(valid => {
            if (valid) {
              let ssss = this.handlTree()
              if (ssss.boole) {
                this.$message.error(ssss.msg)
                return
              }
              let commit = undefined,
                msg = ''
              if (this.$route.query.type == 1 || this.id !== '') {
                commit = updateSave
                msg = '修改保存成功'
              } else if (this.$route.query.type == 2) {
                commit = updateChangeSave
                msg = '方案变更保存成功'
              } else {
                commit = createSave
                msg = '创建保存成功'
              }
              commit(this.ruleForm)
                .then(res => {
                  if (res.code == 200) {
                    this.$message.success(msg)
                    if (res.data !== null) {
                      this.id = res.data.id
                      this.ruleForm.id = res.data.id
                    }
                    resolve()
                  } else {
                    this.$message.error(res.msg)
                  }
                })
                .catch(error => {
                  reject()
                })
            } else {
              reject()
            }
          })
        })
      },

      //提交审核
      handleSubmit() {
        this.ruleForm.stability_instrument_infos = this.formTable.tableData
        this.ruleForm.stability_details = this.conditionsInve
        this.$refs.ruleForm.validate(async valid => {
          if (valid) {
            let ssss = this.handlTree()
            if (ssss.boole) {
              this.$message.error(ssss.msg)
              return
            }
            if (this.ruleForm.id === '') {
              await createSave(this.ruleForm).then(res => {
                if (res.code === 200) {
                  if (res.data !== null) {
                    this.ruleForm.id = res.data.id
                  }
                }
              })
            }
            if (this.$route.query.type == 2) {
              this.openChange = true
            } else {
              updateSave(this.ruleForm).then(res => {
                if (res.code === 200) {
                  subApproval(this.ruleForm.id).then(res => {
                    if (res.code === 200) {
                      this.$message.success('提交审核成功')
                      this.$router.push('/stability/giveUp')
                    } else {
                      this.$message.error(res.msg)
                    }
                  })
                } else {
                  this.$message.error(res.msg)
                }
              })
            }
          } else {
            return false
          }
        })
      },

      //变更审核取消
      cancelChange() {
        this.openChangeForm = {
          id: '',
          change_reason: ''
        }
        this.openChange = false
      },

      //变更审核提交
      submitChange() {
        this.$refs.openChangeForm.validate(valid => {
          if (valid) {
            updateChangeSave(this.ruleForm).then(res => {
              if (res.code === 200) {
                this.openChangeForm.id = res.data.id
                submitChange(this.openChangeForm).then(res => {
                  if (res.code === 200) {
                    this.$message.success('提交变更审批成功')
                    this.$route.params.refresh = true
                    this.$router.push('/stability/giveUp')
                    this.cancelChange()
                  } else {
                    this.$message.error(res.msg)
                  }
                })
              } else {
                this.$message.error(res.msg)
              }
            })
          } else {
            return false
          }
        })
      },

      //样品添加
      hanldAdd: function() {
        this.open = true
        this.title = '样品添加'
      },

      //样品多选事件
      handlSamp: function(val) {
        if (val.length > this.conditionsInve.length) {
          let id = ''
          for (var i = 0; i < val.length; i++) {
            let index = this.conditionsInve.findIndex(a => a.name == val[i])
            if (index == -1) {
              id = val[i]
              break
            }
          }
          let index1 = this.sampleList.findIndex(a => a.id == id)
          if (index1 !== -1) {
            let data = this.sampleList[index1]
            let a = {
              label: data.sample_name,
              stability_sample_info: data,
              name: data.id + '',
              list: [],
              conditions: [],
              inspect_types: []
            }
            this.conditionsInve.push(a)
          }
        } else {
          let id2 = ''
          for (var i = 0; i < this.conditionsInve.length; i++) {
            let index2 = val.findIndex(a => a == this.conditionsInve[i].name)
            if (index2 == -1) {
              id2 = i
              break
            }
          }
          this.conditionsInve.splice(id2, 1)
        }
        console.log(this.conditionsInve,'------------')
      },

      //样品id处理
      handlSampID: function() {
        let aa = this.ruleForm.sample_list
        aa.sort((a, b) => {
          return a.id - b.id
        })
        this.sample_id = aa[aa.length - 1].id
      },

      //样品编辑
      handleEdit: function(val) {
        this.title = '样品编辑'
        this.formOpen = { ...this.sampleList[val] }
        this.openIndex = val
        this.openType = true
        this.open = true
      },

      //样品删除
      handleDelete: function(index) {
        this.sampleList.splice(index, 1)
        if (this.checlSamp.length > 0) {
          this.conditionsInve.splice(index, 1)
        }
        this.ruleForm.sample_list = this.sampleList
        if (this.sampleList.length === 0) {
          this.formOpen.id = 1
        } else {
          this.formOpen.id = this.sampleList[this.sampleList.length - 1].id
        }
      },

      //样品弹框取消
      cancel: function() {
        this.formOpen = {
          sample_name: '',
          sample_type_info: {
            same_type_id: '', //"样品类型id",
            same_type_name: '', //"样品类型名称",
            inspect_projects: []
          },
          sample_batch: '',
          packaging_nu: '',
          packaging_unit: '',
          packaging_nu_unit: '',
          producer: ''
        }
        this.openIndex = undefined
        this.openType = false
        this.open = false
      },

      //样品弹框保存继续
      handlSaveAdd: function() {
        if (this.formOpen.packaging_nu === '') {
          this.formOpen.sample_attrs = this.formOpen.packaging_unit
        } else {
          this.formOpen.sample_attrs =
            this.formOpen.packaging_nu +
            this.formOpen.packaging_nu_unit +
            '/' +
            this.formOpen.packaging_unit
        }

        if (this.sampleList.length > 0) {
          this.formOpen.id = (Number(this.sample_id) + 1) + ''
        }
        this.$refs.formOpen.validate(valid => {
          if (valid) {
            if (this.openType) {
              this.$set(this.sampleList, this.openIndex, this.formOpen)
            } else {
              if (this.sampleList.length > 0) {
                // this.formOpen.id = this.sampleList[this.sampleList.length - 1].id + 1
                this.formOpen.id =( Number(this.sample_id) + 1)
              }
              this.sampleList.push(this.formOpen)
            }
            this.ruleForm.sample_list = this.sampleList
            this.handlSampID()
            this.formOpen = {
              sample_name: '',
              sample_type_info: {
                same_type_id: '', //"样品类型id",
                same_type_name: '', //"样品类型名称",
                inspect_projects: []
              },
              sample_batch: '',
              packaging_nu: '',
              packaging_unit: '',
              packaging_nu_unit: '',
              producer: ''
            }
            this.$nextTick(() => {
              this.$refs.formOpen.clearValidate('sample_type_info.same_type_id')
              this.$refs.formOpen.clearValidate('packaging_nu')
            })
            this.openIndex = undefined
            this.openType = false
          } else {
            return false
          }
        })
        console.log(this.sampleList)
      },

      //样品弹框确定
      submitForm: function() {
        if (this.formOpen.packaging_nu === '') {
          this.formOpen.sample_attrs = this.formOpen.packaging_unit
        } else {
          this.formOpen.sample_attrs =
            this.formOpen.packaging_nu +
            this.formOpen.packaging_nu_unit +
            '/' +
            this.formOpen.packaging_unit
        }
        this.$refs.formOpen.validate(valid => {
          if (valid) {
            if (this.openType) {
              this.$set(this.sampleList, this.openIndex, this.formOpen)
              let index = this.conditionsInve.findIndex(
                a => a.name == this.sampleList[this.openIndex].id
              )
              if (index !== -1) {
                this.conditionsInve[index].label = this.sampleList[
                  this.openIndex
                  ].sample_name
                this.conditionsInve[index].stability_sample_info = this.formOpen
              }
            } else {
              if (this.sampleList.length > 0) {
                //this.formOpen.id = this.sampleList[this.sampleList.length - 1].id + 1
                this.formOpen.id = (Number(this.sample_id) + 1)
              }
              this.sampleList.push(this.formOpen)
            }
            this.cancel()
            this.ruleForm.sample_list = this.sampleList
            this.handlSampID()
          } else {
            return false
          }
        })
        console.log(this.sampleList)
      },

      //删除已选节点
      remove: function(data) {
        for (let i = 0; i < this.conditionsInve.length; i++) {
          if (this.conditionsInve.length === 0) return
          for (let j = 0; j < this.conditionsInve[i].conditions.length; j++) {
            if (this.conditionsInve[i].conditions.length === 0) return
            for ( let k = 0;k < this.conditionsInve[i].conditions[j].conditions.length;k++) {
              let a = this.conditionsInve[i]
              if (a.name === data.name && a.label === data.label) {
                this.conditionsInve.splice(i, 1)
                let index = this.sampleList.findIndex(val => val.id === data.name)
                if (index !== -1) {
                  this.sampleList.splice(index, 1)
                }
              }
              if (this.conditionsInve[i] === undefined) return
              let b = this.conditionsInve[i].conditions[j]
              if (b.name === data.name && b.label === data.label) {
                console.log(  data)
                this.conditionsInve[i].conditions.splice(j, 1)
                let index1 = this.conditionsInve[i].inspect_types.findIndex(val => val.inspect_type.id === data.name)
                let index11 = this.conditionsInve[i].list.findIndex(
                  val => val === data.name
                )
                if (index1 !== -1 && index11 !== -1) {
                  this.conditionsInve[i].inspect_types.splice(index1, 1)
                  this.conditionsInve[i].list.splice(index11, 1)
                }
              }
              let c = this.conditionsInve[i].conditions[j].conditions[k]
              if (c.name === data.name && c.label === data.label) {
                this.conditionsInve[i].conditions[j].conditions.splice(k, 1)
                let index3 = this.conditionsInve[i].inspect_types.findIndex(val =>val.inspect_type.id ===
                  this.conditionsInve[i].conditions[j].name)
                if (index3 !== -1) {
                  let index2 = this.conditionsInve[i].inspect_types[
                    index3
                    ].place_conditions_infos.findIndex(
                    val => val.place_conditions.id === data.name
                  )
                  let index22 = this.conditionsInve[i].conditions[
                    j
                    ].list.findIndex(val => val === data.name)
                  if (index2 !== -1 && index22 !== -1) {
                    this.conditionsInve[i].inspect_types[index3].place_conditions_infos.splice(index2, 1)
                    this.conditionsInve[i].conditions[j].list.splice(index22, 1)
                  }
                }
              }
            }
          }
        }
      },

      //判断节点是否存在
      handlShow: function(node) {
        if (this.$route.query.type == 2) {
          if (node.parent.childNodes.length > 1) {
            return true
          } else {
            return false
          }
        } else {
          return true
        }
        // if (node.parent.childNodes.length > 1) {
        //   return true
        // } else {
        //   return false
        // }
      },

      //添加到列表
      handleAddList: function() {
        this.formTable.tableData.push({
          id: '2', //仪器id",
          instrument_name: 'cdd', //仪器名称",
          instrument_no: '654', //仪器编号",
          brand_model: '西门子', //品牌型号",
          attrs: '22', //参数设置",
          locker_id: '', //保管员id",
          locker_name: '' //保管员名称"
        })
      },

      //下一步
      handlNextStep() {
        this.ruleForm.stability_instrument_infos = this.formTable.tableData
        this.ruleForm.stability_details = this.conditionsInve
        let type = this.$route.query.type || 1
        this.$refs.ruleForm.validate(async valid => {
          if (valid) {
            let ssss = this.handlTree()
            if (ssss.boole) {
              this.$message.error(ssss.msg)
              return
            }
            if (this.ruleForm.id === '') {
              await createSave(this.ruleForm).then(res => {
                if (res.code === 200) {
                  if (res.data !== null) {
                    this.id = res.data.id
                    this.ruleForm.id = res.data.id
                  }
                }else{
                  this.$message.error(res.msg)
                }
              })
            }
            updateSave(this.ruleForm).then(res => {
              if (res.code === 200) {
                this.$router.push({
                  path: '/stability/giveUp/tableDetail',
                  query: { id: this.ruleForm.id, type: type }
                })
              }else{
                this.$message.error(res.msg)
              }
            })
          }
        })

      },

      //验证tree
      handlTree() {
        var boole, msg
        if (this.sampleList.length === 0) {
          msg = '请添加样品'
          boole = true
          return { boole: boole, msg: msg }
        } else {
          let aaa = this.conditionsInve
          if (aaa.length === 0) {
            msg = '请勾选样品'
            boole = true
            return { boole: boole, msg: msg }
          } else {
            for (let i = 0; i < aaa.length; i++) {
              let bbb = aaa[i].conditions
              if (bbb.length === 0) {
                msg = `请勾选${aaa[i].label}的考察类型`
                boole = true
                return { boole: boole, msg: msg }
              } else {
                for (let j = 0; j < bbb.length; j++) {
                  if (bbb[j].conditions.length === 0) {
                    msg = `请勾选${bbb[j].label}的放置条件`
                    boole = true
                    return { boole: boole, msg: msg }
                  }
                }
              }
            }
          }
        }
        return { boole: false }
      }
    }
  }
</script>
<style scoped>
  /* @import url(); 引入css类 */
  .el-card {
    height: 260px;
  }

  ::v-deep .el-card__body {
    height: 100% !important;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
  }

  ::v-deep #scrollbox {
    height: 200px;
    flex: 1 !important;
    overflow-y: auto !important;
    color: #000;
    font-size: 16px;
  }

  ::v-deep #scrollbox::-webkit-scrollbar {
    width: 8px;
    height: 8px;
  }

  ::v-deep #scrollbox::-webkit-scrollbar-thumb {
    border-radius: 100px;
    background: #cccccc;
  }

  ::v-deep #scrollbox::-webkit-scrollbar-track {
    border-radius: 0;
    background: rgba(0, 0, 0, 0.1);
  }

  .ul {
    margin: 0;
    padding: 0;
  }

  .ul li {
    height: 40px;
    line-height: 40px;
    padding-right: 10px;
  }

  .ul li:hover {
    background-color: rgb(248, 248, 248);
    cursor: pointer;
  }

  ::v-deep .el-tabs__item {
    width: 130px;
    text-align: center !important;
  }

  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }

  ::v-deep .table1 tr td {
    padding: 0 !important;
    height: 48px !important;
    overflow: visible !important;
    line-height: 48px;
  }

  ::v-deep .table1 tr td .cell {
    height: 30px !important;
    overflow: visible !important;
    line-height: 30px;
  }

  ::v-deep .item_form {
    overflow: hidden;
  }
</style>
